#-*- coding: utf-8 -*-


import logging
from django.db import models
from django.db.models.fields.files import ImageFieldFile
from django.contrib.auth.models import User
from .utils import upload_image


class Account(models.Model):

    user = models.OneToOneField(User)
    nickname = models.CharField(u'昵称', max_length=40, blank=True, null=True)
    truename = models.CharField(u'实名', max_length=40, blank=True, null=True)
    phone = models.CharField(u'手机号', max_length=20, blank=True, null=True, unique=True)
    avatar = models.ImageField(
        u'头像', upload_to='avatar/%Y-%m-%d',
        default='default/avatar.png',
        blank=True
    )
    active_token = models.CharField(u'验证token', max_length=40, blank=True, null=True)
    is_valid = models.BooleanField(u'是否验证', default=False)
    last_login = models.DateTimeField(u'登录时间', auto_now=True)

    class Meta:
        verbose_name_plural = u'账号'

    def __unicode__(self):
        return 'phone:%s - eamil:%s' % (self.phone, self.user.email)

    def save(self):
        super(Account, self).save()
        filepath = self.avatar.name
        if not (filepath == 'default/avatar.png'):
            status = upload_image(filepath)
            if status['success']:
                self.avatar = ImageFieldFile(self, self.avatar, status['new_filepath'])
            super(Account, self).save()

